<template>
  <div class="serviceNoManage__wrapper">
    <search
      ref="search2"
      :inputTitle="'输入服务号进行查询'"
      @turnPage="turnPage"
      :currentPage="currentPage"
      :count="count"
      @exportMethod="exportAct"
      @inputChange="searchByName"
      :pageSize="pageSize"
      :disabledReload="disabledReload"
      :showAdvSearch="true"
      @advSearch="advSearch"
      @removeBadge="removeBadge"
      :showBatchAdd="true"
    ></search>
    <diyTable
      :tableHeader="tableHeader"
      :tableData="tableData"
      @updata="updata"
      @del="del"
      :loading="tableLoading"
    ></diyTable>
    <leftSlide :visible.sync="leftSlideVisible" :title="slideLeftTitle">
      <editService v-if="isShowEdit" :serviceInfo="serviceInfo" @editRefresh="editRefresh" @cancelClick="cancelClick">
      </editService>
      <add-service
        v-if="isShowAdd"
        :availableService="availableService"
        @addRefresh="addRefresh"
        @cancelClick="cancelClick"
      >
      </add-service>
      <batchAddService
        ref="batchAddService"
        v-if="isShowBatchAdd"
        @refreshService="addRefresh"
        @cancelClick="cancelClick"
        :availableService="availableService"
      >
      </batchAddService>
    </leftSlide>
  </div>
</template>
<script>
import leftSlide from '@/components/ui-modules/newConfig/leftSlide.vue'
import configCompositionTwoWindowStyle from '../../../../ui-modules/config/configCompositionTwoWindowStyle'
// import search from '@/components/business-modules/config/channelConfig/base/search'
import search from '../base/search.vue'
import BreadCrumbConfig from '@/components/ui-modules/breadCrumb/BreadCrumbConfig'
import diyTable from '@/components/business-modules/config/channelConfig/base/diyTable'
import { deepClone, ivrSearch } from '@/utils/m7Utils'
import editService from './editService.vue'
import AddService from './addService'
import batchAddService from './batchAddService.vue'
export default {
  name: 'serviceNoManage',
  data() {
    return {
      name: 'callServiceNo2',
      leftSlideVisible: false,
      disabledReload: true,
      slideLeftTitle: '',
      norSearch: [],
      serviceList: [],
      titleArr: ['服务号管理', '添加服务号'],
      reload: true,
      isShowAdd: false,
      isShowEdit: false,
      isShowBatchAdd: false,
      advSearchData: {
        items: [
          {
            title: '服务号类型',
            type: 'select',
            valueName: 'Type',
            data: [
              { label: '普通', value: 'normal' },
              { label: '轻量级', value: 'lightweight' }
            ]
          },
          {
            title: '服务号',
            type: 'input',
            valueName: 'Exten'
          }
        ],
        form: { Type: '', Exten: '' }
      },
      availableService: [],
      dataList: [],
      count: 0,
      pageSize: 10,
      agents: [],
      operFlag: '',
      currPBX: '',
      currentPage: 1, //   当前页
      tableHeader: [
        { prop: 'Exten', label: '服务号' },
        { prop: 'typeName', label: '服务号类型' },
        { prop: 'DisplayName', label: '别名' },
        { prop: 'UpdateTime', label: '最后更新时间' },
        { prop: 'PBX', label: 'PBX' },
        { prop: '', label: '操作' }
      ], //   自定义 表头
      tableData: [], //  表格数据
      tableLoading: false, //   表格  loading
      isShowAddOrEdit: false, //   右侧  新建或修改 显隐
      inputName: '',
      serviceInfo: {}
    }
  },
  computed: {
    Account() {
      return this.$store.state.session.account.account
    },
    currentPBX() {
      return this.$store.state.config.callCenter.currentPBX
    }
  },
  watch: {
    currentPBX() {
      if (this.$route.meta.title === this.name) {
        this.refresh()
        this.updateSelectService()
      }
    }
  },
  components: {
    AddService,
    configCompositionTwoWindowStyle,
    search,
    BreadCrumbConfig,
    diyTable,
    editService,
    leftSlide,
    batchAddService
  },
  methods: {
    exportAct(val) {
      if (val === 'add') {
        this.addService()
      } else if (val === 'refresh') {
        this.refresh()
      } else if (val === 'active') {
        this.active()
      } else if (val === 'batchAdd') {
        this.batchAdd()
      }
    },
    cancle() {
      this.isShowAdd = false
      this.isShowEdit = false
      this.isShowBatchAdd = false
      this.isShowAddOrEdit = false
    },
    removeBadge() {
      this.operFlag = ''
      // this.$refs.search1.advSearch2()
      this.$refs.search2.advSearch2()
    },
    //      高级搜索
    advSearch(val, flag) {
      this.currentPage = 1
      this.inputName = ''
      let data = {}
      this.isShowAdd = false
      this.isShowEdit = false
      this.isShowBatchAdd = false
      this.isShowAddOrEdit = false
      data.Account = this.$store.state.session.account.account
      val.serviceType && (data.Type = val.serviceType)
      val.serviceNo && (data.Exten = val.serviceNo)
      val.PBX && (data.PBX = val.PBX)
      if (!flag) {
        this.operFlag = ''
      }
      this.search(data)
    },
    //      添加服务号
    addService() {
      this.leftSlideVisible = true
      this.isShowAdd = true
      this.isShowEdit = false
      this.isShowBatchAdd = false
      this.slideLeftTitle = '添加服务号'
      this.availableService = deepClone(this.serviceList)
    },
    batchAdd() {
      this.leftSlideVisible = true
      this.isShowAdd = false
      this.isShowEdit = false
      this.isShowBatchAdd = true
      this.slideLeftTitle = '批量添加服务号'
      this.availableService = deepClone(this.serviceList)
    },
    //      添加服务号成功刷新
    addRefresh(data) {
      this.disabledReload = false
      this.leftSlideVisible = false
      this.reload = false
      let _index = 0
      let temp = deepClone(this.serviceList) || []
      this.serviceList.forEach((item, index) => {
        if (data.Exten) {
          // 单个添加
          if (item === data.Exten) {
            _index = index
          }
        } else {
          // 批量添加外
          data.forEach((item2) => {
            if (item === item2) {
              temp.splice(temp.indexOf(item2), 1)
            }
          })
        }
      })
      if (data.Exten) {
        this.serviceList.splice(_index, 1)
      } else {
        this.serviceList = temp
      }
      this.isShowAdd = false
      this.isShowAddOrEdit = false
      this.operFlag = 'add'
      this.currPBX = data.PBX
      this.$refs.search2.advSearch1()
    },
    roloadIvrSucc() {
      this.reload = true
    },
    editRefresh(data) {
      this.disabledReload = false
      this.leftSlideVisible = false
      this.reload = false
      this.operFlag = 'edit'
      this.currPBX = data.PBX
      this.inputName = ''
      this.isShowAdd = false
      this.isShowEdit = false
      this.isShowAddOrEdit = false
      this.$refs.search2.advSearch1()
    },
    //      刷新
    refresh() {
      this.currentPage = 1
      this.inputName = ''
      this.isShowAdd = false
      this.isShowEdit = false
      this.isShowAddOrEdit = false
      this.operFlag = ''
      this.$refs.search2.advSearch2()
    },
    //      input 搜索
    searchByName(val) {
      console.log(val)
      this.isShowAdd = false
      this.isShowEdit = false
      this.isShowAddOrEdit = false
      this.inputName = val
      this.currentPage = 1
      this.norSearch = ivrSearch(this.dataList, val, ['Exten', 'DisplayName'])
      this.count = this.norSearch.length
      this.tableData = []
      this.handleFakePage(this.norSearch)
      //        this.search()
    },
    //      初始化数据
    search(data1) {
      this.tableData = []
      this.dataList = []
      let _pageArray = []
      this.tableLoading = true
      this.$store.dispatch('queryServiceNo', data1).then((res) => {
        if (res.success) {
          if (res.list) {
            this.tableData = []
            this.count = res.list.length
            if (this.count) {
              let _data = res.list.filter((item) => {
                return item.PBX === this.currPBX
              })
              if (this.operFlag === 'add' || this.operFlag === 'edit' || this.operFlag === 'del') {
                this.$store.commit('SET_IVRMAP_DETAIL', {
                  PBX: this.currPBX,
                  typeName: 'ivr_service_no',
                  data: _data || [],
                  flag: 'data',
                  node: this
                })
              }
              res.list.forEach((item) => {
                if (item.Type === 'normal') {
                  let obj = {
                    typeName: '普通',
                    Account: item.Account,
                    DisplayName: item.DisplayName,
                    Exten: item.Exten,
                    PBX: item.PBX,
                    Schedules: item.Schedules,
                    ToPeer: item.ToPeer,
                    Type: item.Type,
                    UpdateTime: item.UpdateTime,
                    UpdateUser: item.UpdateUser,
                    _id: item._id
                  }
                  _pageArray.push(obj)
                } else {
                  let objL = {
                    typeName: '轻量级',
                    Account: item.Account,
                    DisplayName: item.DisplayName,
                    Exten: item.Exten,
                    PBX: item.PBX,
                    Schedules: item.Schedules,
                    ToPeer: item.ToPeer,
                    Type: item.Type,
                    UpdateTime: item.UpdateTime,
                    UpdateUser: item.UpdateUser,
                    _id: item._id,
                    ToPeerType: item.ToPeerType,
                    IvrProcessId: item.IvrProcessId
                  }
                  _pageArray.push(objL)
                }
              })
              this.dataList = []
              this.handleFakePage(_pageArray)
              this.dataList = deepClone(_pageArray)
            }
          }
          this.tableLoading = false
          //            this.isShowAddOrEdit = false
        }
      })
    },
    handleFakePage(_array) {
      for (let i = (this.currentPage - 1) * 10; i < this.currentPage * 10 && i < _array.length; i++) {
        this.tableData.push(_array[i])
      }
    },
    turnPage(val) {
      this.currentPage = val
      this.operFlag = ''
      this.tableData = []
      if (this.inputName !== '') {
        this.handleFakePage(this.norSearch)
      } else {
        this.handleFakePage(this.dataList)
      }
      //        this.search({Account: this.$store.state.session.account.account})
    },
    //      修改服务号
    updata(val) {
      this.leftSlideVisible = true
      this.isShowAdd = false
      this.slideLeftTitle = '修改服务号'
      if (this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[val.PBX]) {
        this.serviceInfo = val
        this.isShowEdit = true
      } else {
        let data = {}
        data.Account = this.$store.state.session.account.account
        data.PBX = val.PBX
        this.$store.dispatch('getAllNodesByPbxForSkill', data).then((res) => {
          if (res.success) {
            this.serviceInfo = val
            this.isShowEdit = true
          }
        })
      }
    },
    //      删除服务号
    del(val) {
      let data = {}
      if (val.Type === 'normal') {
        data = {
          Account: val.Account,
          PBX: val.PBX,
          _id: val._id,
          Type: val.Type,
          Exten: val.Exten,
          DisplayName: val.DisplayName
        }
      } else {
        data = {
          Account: val.Account,
          PBX: val.PBX,
          _id: val._id,
          Type: val.Type,
          Exten: val.Exten,
          DisplayName: val.DisplayName,
          ToPeer: val.ToPeer,
          ToPeerType: val.ToPeerType,
          IvrProcessId: val.IvrProcessId
        }
      }
      this.$confirm('确定要删除该服务号吗？', this.$t('public.tip'), {
        confirmButtonText: this.$t('public.confirm'),
        cancelButtonText: this.$t('public.cancel'),
        cancelButtonClass: 'primary_btn',
        confirmButtonClass: 'primary_btn',
        type: 'warning'
      })
        .then(() => {
          this.$store.dispatch('deleteServiceNo', data).then((res) => {
            if (res.success) {
              this.operFlag = 'del'
              this.currPBX = data.PBX
              this.$refs.search2.advSearch1()
              this.serviceList.push(val.Exten)
              this.isShowAdd = false
              this.isShowEdit = false
              this.isShowAddOrEdit = false
              this.reload = false
              this.$message({
                message: '成功删除服务号',
                type: 'success'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('public.cancel')
          })
        })
    },
    active() {
      let obj = {}
      obj.PBX = this.currentPBX
      obj.Account = this.Account
      this.$store.dispatch('reloadIvr', obj).then((res) => {
        if (res.success) {
          this.disabledReload = true
          this.$message({
            type: 'success',
            message: this.$t('configLazyLoad.process.effectiveSuccessfully')
          })
        }
      })
    },
    cancelClick() {
      this.isShowAdd = false
      this.isShowEdit = false
      this.isShowBatchAdd = false
      this.leftSlideVisible = false
    },
    updateSelectService() {
      let _service = deepClone(this.$store.state.session.ivrMap[this.currentPBX].data.ivr_available_service_no)
      this.serviceList = []
      _service.forEach((item) => {
        this.serviceList.push(item._id)
      })
    }
  },
  mounted() {},
  beforeMount() {
    this.operFlag = ''
    this.currPBX = ''
    this.search({ Account: this.$store.state.session.account.account, PBX: this.currentPBX })
    let data = {}
    data.Account = this.$store.state.session.account.account
    // data.PBX = this.$store.state.session.user.pbx
    data.PBX = this.currentPBX
    this.updateSelectService()
  },
  deactivated() {
    this.oldPBX = this.currentPBX
  },
  activated() {
    if (this.oldPBX !== this.currentPBX) {
      this.refresh()
    }
  }
}
</script>
<style lang="stylus" scoped>
.serviceNoManage__wrapper
  padding 20px
  .node-manage
   border 1px solid #e7e7eb
   border-bottom 0px
</style>
